package mall

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"private-domain-overseas-service/app/business/api/internal/repository/mall"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/status/bizmall"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzmall"
	"private-domain-overseas-service/tools/ent/hzmallgoods"
	"private-domain-overseas-service/tools/ent/predicate"

	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/app/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MallHasGoodsIconsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 首页存在商品的商城金刚区
func NewMallHasGoodsIconsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MallHasGoodsIconsLogic {
	return &MallHasGoodsIconsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MallHasGoodsIconsLogic) MallHasGoodsIcons() (resp *types.MallResponse, err error) {
	mallDao := mall.NewMallDao(l.ctx, l.svcCtx)
	goodsDao := mall.NewMallGoodsDao(l.ctx, l.svcCtx)

	// 构建条件查询商城
	mallConditions := make([]predicate.HzMall, 0)
	mallConditions = append(mallConditions, hzmall.MallStatusEQ(bizmall.On))
	malls, err := mallDao.MallConditionsAll(mallConditions)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerDataNotFoundError, fmt.Sprintf("查询商城数据失败：%v", err.Error()))
	}

	//组装返回数据
	list := lo.Filter(lo.Map(malls, func(item *ent.HzMall, _ int) *types.MallInfo {
		// 查询商城下是否有上架商品
		mallGoodConditions := []predicate.HzMallGoods{hzmallgoods.GoodsMallIDEQ(int64(item.ID))}
		mallGoodConditions = append(mallGoodConditions, hzmallgoods.GoodsStatusEQ(bizmall.On))
		goodsInfo, _ := goodsDao.MallGoodsConditionsFirst(mallGoodConditions)

		if goodsInfo != nil {
			return &types.MallInfo{
				MallId:   int64(item.ID),
				MallIcon: constant.MallGoodsImage + item.MallIcon,
				MallName: item.MallName,
				MallUrl:  item.MallURL,
			}
		}
		return nil
	}),
		func(item *types.MallInfo, _ int) bool {
			return item != nil
		},
	)

	//返回数据
	resp = &types.MallResponse{
		List: list,
	}

	return resp, nil
}
